import dayjs from 'common/js/day.js'
function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function (n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function (milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function (dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function (number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDate()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function (str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

//除法函数，用来得到精确的除法结果
//说明：javascript的除法结果会有误差，在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
//调用：div(arg1,arg2)
//返回值：arg1除以arg2的精确结果
function div(arg1, arg2) {
  var t1 = 0,
    t2 = 0,
    r1,
    r2;
  try {
    t1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    t1 = 0;
  }
  try {
    t2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    t2 = 0;
  }
  r1 = Number(arg1.toString().replace(".", ""));
  r2 = Number(arg2.toString().replace(".", ""));
  return mul(r1 / r2, Math.pow(10, t2 - t1));
}
//乘法函数，用来得到精确的乘法结果
//说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
//调用：mul(arg1,arg2)
//返回值：arg1乘以arg2的精确结果
function mul(arg1, arg2) {
  var m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString();
  try {
    m += s1.split(".")[1].length;
  } catch (e) {
    m = 0;
  }
  try {
    m += s2.split(".")[1].length;
  } catch (e) {
    m = m || 0;
  }
  return (
    (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) /
    Math.pow(10, m)
  );
}

//加法函数，用来得到精确的加法结果
//说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
//调用：add(arg1,arg2)
//返回值：arg1加上arg2的精确结果
function add(arg1, arg2) {
  var r1, r2, m, n;
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2));
  n = r1 >= r2 ? r1 : r2;
  return ((arg1 * m + arg2 * m) / m).toFixed(n);
}

//减法函数，用来得到精确的减法结果
//说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
//调用：sub(arg1,arg2)
//返回值：arg1减去arg2的精确结果
function sub(arg1, arg2) {
  var r1, r2, m, n;
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2));
  //动态控制精度长度
  n = r1 >= r2 ? r1 : r2;
  return ((arg1 * m - arg2 * m) / m).toFixed(n);
}

function formatFloat(f, digit) {
    digit = digit != null ? digit : 2;
    var m = Math.pow(10, digit);
    return (Math.round(f * m, 10) / m).toFixed(digit);
}
function numToChinese(num){
	switch(num){
		 case 1:
			return '周一'
		 case 2:
		 	return '周二'
		case 3:
			return '周三'
		case 4:
			return '周四'
		case 5:
			return '周五'
		case 6:
			return '周六'
		case 0:
			return '周日'
	}

}
function validIdCard(id) {
	// 1 "验证通过!", 0 //校验不通过
	var format = /^(([1][1-5])|([2][1-3])|([3][1-7])|([4][1-6])|([5][0-4])|([6][1-5])|([7][1])|([8][1-2]))\d{4}(([1][9]\d{2})|([2]\d{3}))(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1]))\d{3}[0-9xX]$/;
	//号码规则校验
	if(!format.test(id)){
		return false;
	}
	//区位码校验
	//出生年月日校验   前正则限制起始年份为1900;
	var year = id.substr(6,4),//身份证年
		month = id.substr(10,2),//身份证月
		date = id.substr(12,2),//身份证日
		time = Date.parse(month+'-'+date+'-'+year),//身份证日期时间戳date
		now_time = Date.parse(new Date()),//当前时间戳
		dates = (new Date(year,month,0)).getDate();//身份证当月天数
	if(time>now_time||date>dates){
		return false;
	}
	//校验码判断
	var c = new Array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);   //系数
	var b = new Array('1','0','X','9','8','7','6','5','4','3','2');  //校验码对照表
	var id_array = id.split("");
	var sum = 0;
	for(var k=0;k<17;k++){
		sum+=parseInt(id_array[k])*parseInt(c[k]);
	}
	if(id_array[17].toUpperCase() != b[sum%11].toUpperCase()){
		return false;
	}
	return true
}

function validateIdCard(idCard){
    var vcity={ 11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",  
            21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",  
            33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",  
            42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",  
            51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",  
            63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"  
           };
    //是否为空
    if(idCard === ''){
        return false;
    }
    //校验长度，类型
    if(isCardNo(idCard) === false){
        return false;
    }
    //检查省份
    if(checkProvince(idCard,vcity) === false){
        return false;
    }
    //校验生日
    if(checkBirthday(idCard) === false){
        return false;
    }
    //检验位的检测
    if(checkParity(idCard) === false){
        return false;
    }
    return true;
}

function isCardNo(card){
    //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
    var reg = /(^\d{15}$)|(^\d{17}(\d|X|x)$)/;
    if(reg.test(card) === false){
        return false;
    }
    return true;
}

function checkProvince(card,vcity){
    var province = card.substr(0,2);
    if(vcity[province] == undefined){
        return false;
    }
    return true;
};

function checkBirthday(card){
    var len = card.length;
    //身份证15位时，次序为省（3位）市（3位）年（2位）月（2位）日（2位）校验位（3位），皆为数字
    if(len == '15'){
        var re_fifteen = /^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/; 
        var arr_data = card.match(re_fifteen);
        var year = arr_data[2];
        var month = arr_data[3];
        var day = arr_data[4];
        var birthday = new Date('19'+year+'/'+month+'/'+day);
        return verifyBirthday('19'+year,month,day,birthday);
    }
    //身份证18位时，次序为省（3位）市（3位）年（4位）月（2位）日（2位）校验位（4位），校验位末尾可能为X
    if(len == '18'){
        var re_eighteen = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X|x)$/;
        var arr_data = card.match(re_eighteen);
        var year = arr_data[2];
        var month = arr_data[3];
        var day = arr_data[4];
        var birthday = new Date(year+'/'+month+'/'+day);
        return verifyBirthday(year,month,day,birthday);
    }
    return false;
};

function verifyBirthday(year,month,day,birthday){
    var now = new Date();
    var now_year = now.getFullYear();
    //年月日是否合理
    if(birthday.getFullYear() == year && (birthday.getMonth() + 1) == month && birthday.getDate() == day)
    {
        //判断年份的范围（0岁到100岁之间)
        var time = now_year - year;
        if(time >= 0 && time <= 100)
        {
            return true;
        }
        return false;
    }
    return false;
}

function checkParity(card){
    //15位转18位
    card = changeFivteenToEighteen(card);
    var len = card.length;
    if(len == '18'){
        var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); 
        var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'); 
        var cardTemp = 0, i, valnum; 
        for(i = 0; i < 17; i ++) { 
            cardTemp += card.substr(i, 1) * arrInt[i]; 
        } 
        valnum = arrCh[cardTemp % 11]; 
        if (valnum == card.substr(17, 1).toLocaleUpperCase()) 
        {
            return true;
        }
        return false;
    }
    return false;
}


function changeFivteenToEighteen(card){
    if(card.length == '15')
    {
        var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); 
        var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'); 
        var cardTemp = 0, i;   
        card = card.substr(0, 6) + '19' + card.substr(6, card.length - 6);
        for(i = 0; i < 17; i ++) 
        { 
            cardTemp += card.substr(i, 1) * arrInt[i]; 
        } 
        card += arrCh[cardTemp % 11]; 
        return card;
    }
    return card;
}
function h(e) {
    return new Date(Date.parse(e.replace(/-/g, "/")));
}
function d(e, t) {
    t || (t = e || "yyyy-MM-dd", e = new Date());
    var n = {
        "M+": e.getMonth() + 1,
        "d+": e.getDate(),
        "h+": e.getHours(),
        "m+": e.getMinutes(),
        "s+": e.getSeconds(),
        "q+": Math.floor((e.getMonth() + 3) / 3),
        S: e.getMilliseconds()
    };
    for (var r in /(y+)/.test(t) && (t = t.replace(RegExp.$1, (e.getFullYear() + "").substr(4 - RegExp.$1.length))), 
    /(w+)/.test(t) && (t = t.replace(RegExp.$1, [ [ "日", "一", "二", "三", "四", "五", "六" ], [ "周日", "周一", "周二", "周三", "周四", "周五", "周六" ], [ "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" ] ][RegExp.$1.length - 1][e.getDay()])), 
    n) new RegExp("(" + r + ")").test(t) && (t = t.replace(RegExp.$1, 1 == RegExp.$1.length ? n[r] : ("00" + n[r]).substr(("" + n[r]).length)));
    return t;
}
function addDay(e, t, n) {
	var r = t || new Date();
	n = n || "yyyy-MM-dd", "string" != typeof r && "number" != typeof r || (r = h(t));
	var o = 864e5 * e, i = new Date(r.getTime() + o);
	return {
		date: i,
		day: d(i, n)
	};
}
function getWeek(e) {
	return [ "周日", "周一", "周二", "周三", "周四", "周五", "周六" ][e];
}

function dateDiff()  {
        var e, t, n, r, o = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : "", i = arguments.length > 1 ? arguments[1] : void 0, a = arguments.length > 2 ? arguments[2] : void 0;
        return a = null == a || a, "" == o ? "" : 
		(e = o.split("-"),
		 t = new Date(e[0], e[1] - 1, e[2]), 
        2 == arguments.length && ("boolean" == typeof i ? a = i : i =dayjs().format('YYYY-MM-DD')), 
        1 == arguments.length && (
		i = dayjs().format('YYYY-MM-DD')), e = i.split("-"), 
        n = new Date(e[0], e[1] - 1, e[2]), 
		r = parseInt(Math.abs(t - n) / 1e3 / 60 / 60 / 24), 
        t - n >= 0 ? 0 === r ? "今天" : 1 === r ? "明天" : 2 === r ? "后天" : a ? [ "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" ][t.getDay()] : "" : "");
}

function a(e) {
    return "string" == typeof e && (e = new Date(e.replace(/\..*$/, "").replace(/-/g, "/").replace(/\+/g, " "))), 
    new Date(e);
}
 function getDiffDate() {
	var e = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : new Date(), t = arguments.length > 1 ? arguments[1] : void 0, n = a(e), r = a(t), o = [];
	for (console.log(n, r); r.getTime() - n.getTime() >= 0; ) {
		var i = n.getMonth() + 1, c = n.getDate(), u = n.getFullYear(), s = i < 10 ? "0".concat(i) : i + "", l = c < 10 ? "0".concat(c) : c + "";
		o.push(u + "-" + s + "-" + l), n.setDate(n.getDate() + 1);
	}
	return o;
}

function formatDate(e, t) {
    t || (t = e || "yyyy-MM-dd", e = new Date());
    var n = {
        "M+": e.getMonth() + 1,
        "d+": e.getDate(),
        "h+": e.getHours(),
        "m+": e.getMinutes(),
        "s+": e.getSeconds(),
        "q+": Math.floor((e.getMonth() + 3) / 3),
        S: e.getMilliseconds()
    };
    for (var r in /(y+)/.test(t) && (t = t.replace(RegExp.$1, (e.getFullYear() + "").substr(4 - RegExp.$1.length))), 
    /(w+)/.test(t) && (t = t.replace(RegExp.$1, [ [ "日", "一", "二", "三", "四", "五", "六" ], [ "周日", "周一", "周二", "周三", "周四", "周五", "周六" ], [ "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" ] ][RegExp.$1.length - 1][e.getDay()])), 
    n) new RegExp("(" + r + ")").test(t) && (t = t.replace(RegExp.$1, 1 == RegExp.$1.length ? n[r] : ("00" + n[r]).substr(("" + n[r]).length)));
    return t;
}
function parseDate(e) {
    return new Date(Date.parse(e.replace(/-/g, "/")));
}
function getAge(identify) {
	var UUserCard = identify;
	if (UUserCard != null && UUserCard != '') {
		//获取年龄
		var myDate = new Date();
		var month = myDate.getMonth() + 1;
		var day = myDate.getDate();
		var age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;
		if (UUserCard.substring(10, 12) < month || UUserCard.substring(10, 12) == month && UUserCard.substring(12, 14) <= day) {
			age++;
		}
		return age;
//				
	}
}

	/**
	 * 用户信息分享海报
	 * @param array arr2 海报素材  1背景 0二维码
	 * @param string nickname 昵称
	 * @param string sitename 价格
	 * @param function successFn 回调函数
	 * 
	 * 
	 */
	function userPosterCanvas(arr2, nickname, sitename, index, w, h, successFn) {
		let that = this;
		const ctx = uni.createCanvasContext('myCanvas' + index);
		ctx.clearRect(0, 0, 0, 0);
		/**
		 * 只能获取合法域名下的图片信息,本地调试无法获取
		 * 
		 */
		uni.getImageInfo({
			src: arr2[1],
			success: function(res) {
				const WIDTH = res.width;
				const HEIGHT = res.height;
				ctx.fillStyle = '#fff';
				ctx.fillRect(0, 0, w, h);
				ctx.drawImage(arr2[1], 0, 0, w, h);
				ctx.setTextAlign('left')
				ctx.setFontSize(12);
				ctx.setFillStyle('#333');

				// x:240 y:426
				let codex = 0.1906
				let codey = 0.7746
				let codeSize = 0.21666
				let namex = 0.4283
				let namey = 0.8215
				let markx = 0.4283
				let marky = 0.8685
				ctx.drawImage(arr2[0], w * codex, h * codey, w * codeSize, w * codeSize);
				if (w < 270) {
					ctx.setFontSize(8);
				} else {
					ctx.setFontSize(10);
				}
				ctx.fillText(nickname, w * namex, h * namey);
				if (w < 270) {
					ctx.setFontSize(8);
				} else {
					ctx.setFontSize(10);
				}
				ctx.fillText('邀请您加入' + sitename, w * markx, h * marky);
				ctx.save();
				ctx.draw(true, function() {
					uni.canvasToTempFilePath({
						canvasId: 'myCanvas' + index,
						fileType: 'png',
						quality: 1,
						success: function(res) {
							successFn && successFn(res.tempFilePath);
						}
					})
				});
			},
			fail: function(err) {
				uni.hideLoading();
				that.Tips({
					title: '无法获取图片信息'
				});
			}
		})
	}

module.exports = {
	formatTime: formatTime,
	formatLocation: formatLocation,
	dateUtils: dateUtils,
	div: div,
	mul: mul,
	add: add,
	sub: sub,
	formatFloat: formatFloat,
	validIdCard: validIdCard,
	numToChinese:numToChinese,
	validateIdCard: validateIdCard,
	addDay: addDay,
	getWeek: getWeek,
	dateDiff: dateDiff,
	getDiffDate: getDiffDate,
	formatDate: formatDate,
	parseDate: parseDate,
	getAge: getAge,
	userPosterCanvas: userPosterCanvas
}
